package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.result.R;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /*
    * 短信发送
    * */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        //获取用户手机号码
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)) {
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("code={}",code);
            //发送短信
            //SMSUtils.sendMessage(phone, code);
            //将用户信息存入session中
            request.getSession().setAttribute(phone,code);

            return R.success("发送成功！");
        }

        return R.error("发送失败！");
    }

    /*
     * 用户登陆
     * */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpServletRequest request) {
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码    map.get("code").toString();
        String code = "123456";

        //从session中取出验证码   request.getSession().getAttribute("code");
        Object codeInSession = "123456";

        //判断验证码是否相等
        if (codeInSession != null && codeInSession.equals(code)) {
            //判断是否为首次登陆
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, phone);

            User user = userService.getOne(lqw);

            if (user == null) {
                user = new User();
                user.setPhone(phone);

                userService.save(user);
            }
            request.getSession().setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登录失败！");
    }

    /*
     * 用户登出功能
     * */
    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");

        return R.success("退出成功");
    }
}
